/**
 * @file log_add_exp_custom.cpp
 *
 * Copyright (C) 2022-2024. Huawei Technologies Co., Ltd. All rights reserved.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
#include "kernel_operator.h"
constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue

class KernelLog_Add_Exp {
public:
    __aicore__ inline KernelLog_Add_Exp() {}
    __aicore__ inline void Init(GM_ADDR x, GM_ADDR y, GM_ADDR z, uint32_t totalLength, uint32_t tileNum)
    {
        this->blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum = tileNum;
        this->tileLength = this->blockLength / tileNum / BUFFER_NUM;

        xGm.SetGlobalBuffer((__gm__ DTYPE_X *)x + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        yGm.SetGlobalBuffer((__gm__ DTYPE_Y *)y + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        zGm.SetGlobalBuffer((__gm__ DTYPE_Z *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        pipe.InitBuffer(inQueueX, BUFFER_NUM, this->tileLength * sizeof(DTYPE_X));
        pipe.InitBuffer(inQueueY, BUFFER_NUM, this->tileLength * sizeof(DTYPE_Y));
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(DTYPE_Z));
        pipe.InitBuffer(tmpBuffer1, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer2, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer3, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer4, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer5, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer6, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer7, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer8, this->tileLength * sizeof(float));
        pipe.InitBuffer(tmpBuffer9, this->tileLength * sizeof(float));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<DTYPE_X> xLocal = inQueueX.AllocTensor<DTYPE_X>();
        AscendC::LocalTensor<DTYPE_Y> yLocal = inQueueY.AllocTensor<DTYPE_Y>();
        AscendC::DataCopy(xLocal, xGm[progress * this->tileLength], this->tileLength);
        AscendC::DataCopy(yLocal, yGm[progress * this->tileLength], this->tileLength);
        inQueueX.EnQue(xLocal);
        inQueueY.EnQue(yLocal);
    }
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<DTYPE_X> xLocal = inQueueX.DeQue<DTYPE_X>();
        AscendC::LocalTensor<DTYPE_Y> yLocal = inQueueY.DeQue<DTYPE_Y>();
        AscendC::LocalTensor<DTYPE_Z> zLocal = outQueueZ.AllocTensor<DTYPE_Z>();
        AscendC::LocalTensor<float> max_xy = tmpBuffer1.Get<float>();
        AscendC::LocalTensor<float> sub_xy = tmpBuffer2.Get<float>();
        AscendC::LocalTensor<float> abs_xy = tmpBuffer3.Get<float>();
        AscendC::LocalTensor<float> exp_xy = tmpBuffer4.Get<float>();
        AscendC::LocalTensor<float> tmpTensor = tmpBuffer5.Get<float>();
        AscendC::LocalTensor<float> add_xy = tmpBuffer6.Get<float>();
        AscendC::LocalTensor<float> ln_xy = tmpBuffer7.Get<float>();

        uint8_t repeat = (uint8_t)tileLength / 64;
        //ln(e^x + e^y) -> max(x,y) + ln(1 + e ^ (-|x−y|) ) 避免指数爆炸
        // max(x, y)
        AscendC::Max(max_xy, xLocal, yLocal, 64, repeat, { 1, 1, 1, 8, 8, 8 });

        // - | x - y |
        AscendC::Sub(sub_xy, xLocal, yLocal, 64, repeat, { 1, 1, 1, 8, 8, 8 });
        AscendC::Abs(abs_xy, sub_xy, 64, repeat, { 1, 1, 8, 8 });
        AscendC::Muls(abs_xy, abs_xy, (float)(-1.0), 64, repeat, { 1, 1, 8, 8 });

        // e ^ ( - |x−y| ) 
        AscendC::Exp(exp_xy, abs_xy, this->tileLength);

        // 1 + e ^ (-|x−y|)
        float scalar = 1.0;
        AscendC::Duplicate(tmpTensor, scalar, 64, repeat, 1, 8);
        AscendC::Add(add_xy, exp_xy, tmpTensor, 64, repeat, { 1, 1, 1, 8, 8, 8 });

        // ln[ 1 + e ^ (-|x−y|) ]
        AscendC::Ln(ln_xy, add_xy, 64, repeat, { 1, 1, 8, 8 });

        // max(x,y) + ln( 1 + e ^ (-|x−y|) )
        AscendC::Add(zLocal, max_xy, ln_xy, 64, repeat, { 1, 1, 1, 8, 8, 8 });

        outQueueZ.EnQue<DTYPE_Z>(zLocal);
        inQueueX.FreeTensor(xLocal);
        inQueueY.FreeTensor(yLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<DTYPE_Z> zLocal = outQueueZ.DeQue<DTYPE_Z>();
        AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueX, inQueueY;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuffer1, tmpBuffer2, tmpBuffer3, tmpBuffer4, tmpBuffer5, tmpBuffer6, tmpBuffer7;
    AscendC::TBuf<AscendC::QuePosition::VECCALC> tmpBuffer8, tmpBuffer9;
    AscendC::GlobalTensor<DTYPE_X> xGm;
    AscendC::GlobalTensor<DTYPE_Y> yGm;
    AscendC::GlobalTensor<DTYPE_Z> zGm;
    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
};

extern "C" __global__ __aicore__ void log_add_exp_custom(GM_ADDR x, GM_ADDR y, GM_ADDR z, GM_ADDR workspace, GM_ADDR tiling)
{
    GET_TILING_DATA(tiling_data, tiling);
    KernelLog_Add_Exp op;
    op.Init(x, y, z, tiling_data.totalLength, tiling_data.tileNum);
    op.Process();
}